package com.ydlclass.serialization.hession;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.ydlclass.exception.SerializeException;
import com.ydlclass.serialization.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;


/**
 * @author it楠老师
 * @createTime 2023-03-09
 */
@Slf4j
public class HessionSerializer implements Serializer {
    @Override
    public byte[] serialize(Object obj) {
        if(log.isDebugEnabled()){
            log.debug("Serialization is being done using hession2.");
        }
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
            hessianOutput.writeObject(obj);

            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            log.error("对象[{}]序列化过程发生了异常！",obj,e);
            throw new SerializeException("An exception occurred while implementing serialization using hession.");
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if(log.isDebugEnabled()){
            log.debug("Deserialization is being done using hession2.");
        }
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            HessianInput hessianInput = new HessianInput(byteArrayInputStream);
            Object o = hessianInput.readObject();

            return clazz.cast(o);

        } catch (Exception e) {
            throw new SerializeException("An exception occurred while implementing deserialization using hession.");
        }

    }
    @Override
    public byte getCode() {
        return 0;
    }
}
